package main

import (
	"bytes"
	"crypto/cipher"
	"crypto/rand"
	"crypto/sha256"
	"embed"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"math/big"
	mathrand "math/rand"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"time"

	"crypto/hmac"
	"crypto/md5"
	"crypto/sha1"

	"github.com/dop251/goja"
	"github.com/tjfoc/gmsm/sm4"
)

type Server struct {
	urlHistory []RequestHistoryItem
	assets     embed.FS
}

// 请求历史记录项
type RequestHistoryItem struct {
	ID           int64             `json:"id"`
	Timestamp    string            `json:"timestamp"`
	OriginalUrl  string            `json:"originalUrl"`
	ProcessedUrl string            `json:"processedUrl"`
	Method       string            `json:"method"`
	Headers      map[string]string `json:"headers"`
	Body         string            `json:"body"`
	Options      RequestOptions    `json:"options"`
	Name         string            `json:"name"`
}

type RequestData struct {
	Method  string            `json:"method"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers"`
	Body    string            `json:"body"`
	Options RequestOptions    `json:"options"`
}

type RequestOptions struct {
	AddTimestamp        bool   `json:"addTimestamp"`
	TimestampField      string `json:"timestampField"`
	TimestampPos        string `json:"timestampPos"`
	TimestampUnit       string `json:"timestampUnit"` // 新增：时间戳单位 "milliseconds" 或 "seconds"
	AddNonce            bool   `json:"addNonce"`
	NonceField          string `json:"nonceField"`
	NoncePos            string `json:"noncePos"`
	NonceLength         int    `json:"nonceLength"`
	AddAppId            bool   `json:"addAppId"`
	AppIdField          string `json:"appIdField"`
	AppIdPos            string `json:"appIdPos"`
	AppIdValue          string `json:"appIdValue"`
	AddSignature        bool   `json:"addSignature"`
	SignatureField      string `json:"signatureField"`
	SignaturePos        string `json:"signaturePos"`
	SignatureKey        string `json:"signatureKey"`
	UseCustomSignature  bool   `json:"useCustomSignature"`
	CustomSignatureCode string `json:"customSignatureCode"`
	EncryptBody         bool   `json:"encryptBody"`
	DecryptResponse     bool   `json:"decryptResponse"`
	SM4Key              string `json:"sm4Key"`
	SM4IV               string `json:"sm4IV"`
}

type ResponseData struct {
	Status       int               `json:"status"`
	StatusText   string            `json:"statusText"`
	Headers      map[string]string `json:"headers"`
	Body         string            `json:"body"`
	Duration     int64             `json:"duration"`
	ProcessedUrl string            `json:"processedUrl,omitempty"`
	Error        string            `json:"error,omitempty"`
}

func NewServer(assets embed.FS) *Server {
	server := &Server{
		urlHistory: make([]RequestHistoryItem, 0),
		assets:     assets,
	}
	// 启动时加载URL历史记录
	server.loadUrlHistory()
	return server
}

func (s *Server) Start() {
	// 使用自定义路由处理器
	http.HandleFunc("/", s.routeHandler)

	fmt.Println("服务器启动在 http://localhost:8080")
	http.ListenAndServe(":8080", nil)
}

// 自定义路由处理器
func (s *Server) routeHandler(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

	// API路由
	switch {
	case path == "/api/request":
		s.handleRequest(w, r)
	case path == "/api/settings":
		s.handleSettings(w, r)
	case path == "/api/history":
		s.handleHistory(w, r)
	case path == "/api/tabs" || path == "/api/tabs/list" || strings.HasPrefix(path, "/api/tabs/"):
		s.handleTabs(w, r)
	case path == "/api/encrypt":
		s.handleEncrypt(w, r)
	case path == "/api/decrypt":
		s.handleDecrypt(w, r)
	case strings.HasPrefix(path, "/api/environment"):
		s.handleEnvironment(w, r)
	default:
		// 静态文件服务
		s.serveStatic(w, r)
	}
}

// 获取应用数据目录（server包内部使用）
func getServerAppDataDir() (string, error) {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(homeDir, "AppData", "Local", "Hermes"), nil
}

func (s *Server) serveStatic(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

	if path == "/" {
		path = "/index.html"
	}

	content, err := s.assets.ReadFile("web" + path)
	if err != nil {
		http.NotFound(w, r)
		return
	}

	// 设置正确的Content-Type
	if strings.HasSuffix(path, ".html") {
		w.Header().Set("Content-Type", "text/html")
	} else if strings.HasSuffix(path, ".css") {
		w.Header().Set("Content-Type", "text/css")
	} else if strings.HasSuffix(path, ".js") {
		w.Header().Set("Content-Type", "application/javascript")
	}

	w.Write(content)
}

func (s *Server) SendRequest(reqData RequestData) ResponseData {
	start := time.Now()

	// 这里先不添加历史记录，等请求完成后再添加

	// 处理请求选项
	processedReq, err := s.processRequestOptions(reqData)
	if err != nil {
		return ResponseData{Error: err.Error(), Headers: map[string]string{}}
	}

	// 创建HTTP请求
	var body io.Reader
	if processedReq.Body != "" {
		body = strings.NewReader(processedReq.Body)
	}

	req, err := http.NewRequest(processedReq.Method, processedReq.URL, body)
	if err != nil {
		return ResponseData{Error: err.Error(), Headers: map[string]string{}}
	}

	// 设置请求头
	for key, value := range processedReq.Headers {
		req.Header.Set(key, value)
	}

	// 发送请求
	client := &http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return ResponseData{Error: err.Error(), Headers: map[string]string{}}
	}
	defer resp.Body.Close()

	// 读取响应
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return ResponseData{Error: err.Error(), Headers: map[string]string{}}
	}

	// 处理响应解密
	bodyStr := string(respBody)
	if reqData.Options.DecryptResponse && reqData.Options.SM4Key != "" {
		if decrypted, err := s.decryptSM4Response(bodyStr, reqData.Options.SM4Key, reqData.Options.SM4IV); err == nil {
			bodyStr = decrypted
		}
	}

	// 构建响应头映射
	headers := make(map[string]string)
	for key, values := range resp.Header {
		headers[key] = strings.Join(values, ", ")
	}

	duration := time.Since(start).Milliseconds()

	// 请求成功后添加到历史记录
	s.addToHistory(reqData, processedReq.URL)

	return ResponseData{
		Status:       resp.StatusCode,
		StatusText:   resp.Status,
		Headers:      headers,
		Body:         bodyStr,
		Duration:     duration,
		ProcessedUrl: processedReq.URL,
	}
}

func (s *Server) processRequestOptions(reqData RequestData) (RequestData, error) {
	result := reqData

	// 解析URL
	parsedURL, err := url.Parse(reqData.URL)
	if err != nil {
		return result, err
	}

	query := parsedURL.Query()
	headers := make(map[string]string)
	for k, v := range reqData.Headers {
		headers[k] = v
	}

	// 添加时间戳
	if reqData.Options.AddTimestamp {
		var timestamp string
		// 根据配置选择时间戳单位，默认为毫秒
		if reqData.Options.TimestampUnit == "seconds" {
			timestamp = strconv.FormatInt(time.Now().Unix(), 10)
		} else {
			// 默认使用毫秒
			timestamp = strconv.FormatInt(time.Now().UnixMilli(), 10)
		}

		field := reqData.Options.TimestampField
		if field == "" {
			field = "timestamp"
		}

		if reqData.Options.TimestampPos == "header" {
			headers[field] = timestamp
		} else {
			query.Set(field, timestamp)
		}
	}

	// 添加Nonce
	if reqData.Options.AddNonce {
		nonce := s.generateNonce(reqData.Options.NonceLength)
		field := reqData.Options.NonceField
		if field == "" {
			field = "nonce"
		}

		if reqData.Options.NoncePos == "header" {
			headers[field] = nonce
		} else {
			query.Set(field, nonce)
		}
	}

	// 添加AppId
	if reqData.Options.AddAppId && reqData.Options.AppIdValue != "" {
		field := reqData.Options.AppIdField
		if field == "" {
			field = "appId"
		}

		if reqData.Options.AppIdPos == "header" {
			headers[field] = reqData.Options.AppIdValue
		} else {
			query.Set(field, reqData.Options.AppIdValue)
		}
	}

	// 更新URL
	parsedURL.RawQuery = query.Encode()
	result.URL = parsedURL.String()
	result.Headers = headers

	fmt.Println("[签名调试] 最终URL:", result.URL)
	fmt.Println("[签名调试] 最终Headers:", result.Headers)
	fmt.Println("[签名调试] 最终Body:", result.Body)

	// 添加签名
	if reqData.Options.AddSignature {
		signature, err := s.generateSignature(result, reqData.Options)
		if err != nil {
			return result, err
		}

		field := reqData.Options.SignatureField
		if field == "" {
			field = "signature"
		}

		if reqData.Options.SignaturePos == "header" {
			result.Headers[field] = signature
		} else {
			parsedURL, _ := url.Parse(result.URL)
			query := parsedURL.Query()
			query.Set(field, signature)
			parsedURL.RawQuery = query.Encode()
			result.URL = parsedURL.String()
		}
	}

	// 加密请求体
	if reqData.Options.EncryptBody && reqData.Body != "" && reqData.Options.SM4Key != "" {
		encrypted, err := s.encryptSM4Body(reqData.Body, reqData.Options.SM4Key, reqData.Options.SM4IV)
		if err != nil {
			return result, err
		}
		result.Body = encrypted
	}

	return result, nil
}

func (s *Server) generateNonce(length int) string {
	if length <= 0 {
		length = 16
	}

	const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
	b := make([]byte, length)
	for i := range b {
		n, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
		b[i] = charset[n.Int64()]
	}
	return string(b)
}

func (s *Server) generateSignature(reqData RequestData, options RequestOptions) (string, error) {
	var signatureKey string
	var globalSettings map[string]interface{} // 提前定义，便于后续 debug

	if options.UseCustomSignature {
		// 勾选了自定义签名，允许用自定义密钥
		signatureKey = options.SignatureKey
		if signatureKey == "" {
			// 没有自定义密钥，尝试全局
			var err error
			globalSettings, err = s.LoadSettings()
			if err == nil {
				if globalKey, ok := globalSettings["defaultSignatureKey"].(string); ok && globalKey != "" {
					signatureKey = globalKey
				}
			}
		}
	} else {
		// 未勾选自定义签名，只允许用全局密钥
		var err error
		globalSettings, err = s.LoadSettings()
		if err == nil {
			if globalKey, ok := globalSettings["defaultSignatureKey"].(string); ok && globalKey != "" {
				signatureKey = globalKey
			}
		}
	}

	if signatureKey == "" {
		fmt.Println("[签名调试] 未配置签名密钥, 全局配置内容:", globalSettings)
		return "", fmt.Errorf("未配置签名密钥")
	}

	// 如果使用自定义签名配置且有自定义代码，则使用自定义逻辑
	if options.UseCustomSignature && options.CustomSignatureCode != "" {
		vm := goja.New()
		parsedURL, _ := url.Parse(reqData.URL)
		params := map[string]interface{}{}
		for key, values := range parsedURL.Query() {
			if len(values) > 0 {
				params[key] = values[0]
			}
		}
		if reqData.Method == "POST" && strings.Contains(reqData.Headers["Content-Type"], "application/x-www-form-urlencoded") {
			formData, err := url.ParseQuery(reqData.Body)
			if err == nil {
				for key, values := range formData {
					if len(values) > 0 {
						params[key] = values[0]
					}
				}
			}
		}
		vm.Set("params", params)
		vm.Set("key", signatureKey)
		vm.Set("body", reqData.Body)
		// 注入常用hash函数
		vm.Set("sha256Hex", func(s string) string {
			hash := sha256.Sum256([]byte(s))
			return fmt.Sprintf("%x", hash)
		})
		vm.Set("hash", func(s string) string {
			hash := sha256.Sum256([]byte(s))
			return fmt.Sprintf("%x", hash)
		})
		vm.Set("sha256", func(s string) string {
			hash := sha256.Sum256([]byte(s))
			return fmt.Sprintf("%x", hash)
		})
		// 注入常用签名辅助函数
		vm.Set("md5Hex", func(s string) string {
			return fmt.Sprintf("%x", md5.Sum([]byte(s)))
		})
		vm.Set("sha1Hex", func(s string) string {
			return fmt.Sprintf("%x", sha1.Sum([]byte(s)))
		})
		vm.Set("hmacSha256", func(s, key string) string {
			h := hmac.New(sha256.New, []byte(key))
			h.Write([]byte(s))
			return fmt.Sprintf("%x", h.Sum(nil))
		})
		vm.Set("hmacMd5", func(s, key string) string {
			h := hmac.New(md5.New, []byte(key))
			h.Write([]byte(s))
			return fmt.Sprintf("%x", h.Sum(nil))
		})
		vm.Set("base64Encode", func(s string) string {
			return base64.StdEncoding.EncodeToString([]byte(s))
		})
		vm.Set("urlEncode", func(s string) string {
			return url.QueryEscape(s)
		})
		vm.Set("toUpperCase", func(s string) string {
			return strings.ToUpper(s)
		})
		vm.Set("toLowerCase", func(s string) string {
			return strings.ToLower(s)
		})
		vm.Set("jsonStringify", func(v interface{}) string {
			b, _ := json.Marshal(v)
			return string(b)
		})
		jsCode := options.CustomSignatureCode + "\ngenerateSignature(params, key, body);"
		v, err := vm.RunString(jsCode)
		if err != nil {
			return "", fmt.Errorf("自定义签名代码执行出错: %v", err)
		}
		if str, ok := v.Export().(string); ok {
			return str, nil
		} else {
			return "", fmt.Errorf("自定义签名代码未返回字符串")
		}
	}
	// 未勾选自定义签名时，尝试全局自定义签名代码
	if !options.UseCustomSignature {
		var globalCode string
		if globalSettings == nil {
			var err error
			globalSettings, err = s.LoadSettings()
			if err != nil {
				globalSettings = map[string]interface{}{}
			}
		}
		if code, ok := globalSettings["defaultCustomSignatureCode"].(string); ok && code != "" {
			globalCode = code
		}
		if globalCode != "" {
			vm := goja.New()
			parsedURL, _ := url.Parse(reqData.URL)
			params := map[string]interface{}{}
			for key, values := range parsedURL.Query() {
				if len(values) > 0 {
					params[key] = values[0]
				}
			}
			if reqData.Method == "POST" && strings.Contains(reqData.Headers["Content-Type"], "application/x-www-form-urlencoded") {
				formData, err := url.ParseQuery(reqData.Body)
				if err == nil {
					for key, values := range formData {
						if len(values) > 0 {
							params[key] = values[0]
						}
					}
				}
			}
			vm.Set("params", params)
			vm.Set("key", signatureKey)
			jsCode := globalCode + "\ngenerateSignature(params, key);"
			v, err := vm.RunString(jsCode)
			if err != nil {
				return "", fmt.Errorf("全局自定义签名代码执行出错: %v", err)
			}
			if str, ok := v.Export().(string); ok {
				return str, nil
			} else {
				return "", fmt.Errorf("全局自定义签名代码未返回字符串")
			}
		}
	}

	// 使用默认签名算法
	return s.generateDefaultSignature(reqData, signatureKey)
}

func (s *Server) generateDefaultSignature(reqData RequestData, signatureKey string) (string, error) {
	// 解析URL获取查询参数
	parsedURL, err := url.Parse(reqData.URL)
	if err != nil {
		return "", err
	}

	params := make(map[string]string)

	// 添加查询参数
	for key, values := range parsedURL.Query() {
		if len(values) > 0 {
			params[key] = values[0]
		}
	}

	// 如果是POST请求且有表单数据，也加入签名
	if reqData.Method == "POST" && strings.Contains(reqData.Headers["Content-Type"], "application/x-www-form-urlencoded") {
		formData, err := url.ParseQuery(reqData.Body)
		if err == nil {
			for key, values := range formData {
				if len(values) > 0 {
					params[key] = values[0]
				}
			}
		}
	}

	// 按键名排序
	keys := make([]string, 0, len(params))
	for key := range params {
		if strings.EqualFold(key, "signature") { // 跳过 signature 字段，忽略大小写
			continue
		}
		keys = append(keys, key)
	}
	sort.Strings(keys)

	// 拼接参数值
	var builder strings.Builder
	for _, key := range keys {
		builder.WriteString(params[key])
	}

	// 添加签名密钥
	builder.WriteString(signatureKey)

	// 生成SHA256哈希
	hash := sha256.Sum256([]byte(builder.String()))
	return fmt.Sprintf("%x", hash), nil
}

func (s *Server) encryptSM4Body(body, key, iv string) (string, error) {
	if len(key) != 16 {
		return "", fmt.Errorf("SM4密钥长度必须为16字节")
	}
	if len(iv) != 16 {
		return "", fmt.Errorf("SM4 IV长度必须为16字节")
	}

	// 使用CBC模式加密
	sm4Cipher, err := sm4.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	// PKCS7填充
	plaintext := []byte(body)
	blockSize := sm4Cipher.BlockSize()
	padding := blockSize - len(plaintext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	plaintext = append(plaintext, padtext...)

	// CBC模式加密
	encrypted := make([]byte, len(plaintext))
	mode := cipher.NewCBCEncrypter(sm4Cipher, []byte(iv))
	mode.CryptBlocks(encrypted, plaintext)

	return base64.StdEncoding.EncodeToString(encrypted), nil
}

func (s *Server) decryptSM4Response(body, key, iv string) (string, error) {
	if len(key) != 16 {
		return "", fmt.Errorf("SM4密钥长度必须为16字节")
	}
	if len(iv) != 16 {
		return "", fmt.Errorf("SM4 IV长度必须为16字节")
	}

	encrypted, err := base64.StdEncoding.DecodeString(body)
	if err != nil {
		return "", err
	}

	// 使用CBC模式解密
	sm4Cipher, err := sm4.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	// CBC模式解密
	decrypted := make([]byte, len(encrypted))
	mode := cipher.NewCBCDecrypter(sm4Cipher, []byte(iv))
	mode.CryptBlocks(decrypted, encrypted)

	// 去除PKCS7填充
	padding := int(decrypted[len(decrypted)-1])
	if padding > len(decrypted) || padding == 0 {
		return "", fmt.Errorf("无效的填充")
	}

	// 验证填充
	for i := len(decrypted) - padding; i < len(decrypted); i++ {
		if decrypted[i] != byte(padding) {
			return "", fmt.Errorf("无效的填充")
		}
	}

	return string(decrypted[:len(decrypted)-padding]), nil
}

func (s *Server) addToHistory(reqData RequestData, processedUrl string) {
	// 每次请求都新增一条历史记录，不再检查重复
	historyItem := RequestHistoryItem{
		ID:           time.Now().UnixNano(),
		Timestamp:    time.Now().Format("2006-01-02 15:04:05"),
		OriginalUrl:  reqData.URL,
		ProcessedUrl: processedUrl,
		Method:       reqData.Method,
		Headers:      reqData.Headers,
		Body:         reqData.Body,
		Options:      reqData.Options,
		Name:         extractNameFromUrl(reqData.URL),
	}

	// 添加到历史记录开头
	s.urlHistory = append([]RequestHistoryItem{historyItem}, s.urlHistory...)

	// 限制历史记录数量
	if len(s.urlHistory) > 100 {
		s.urlHistory = s.urlHistory[:100]
	}

	// 保存到文件
	s.saveUrlHistory()
}

// 从URL提取名称的辅助函数
func extractNameFromUrl(urlStr string) string {
	if urlStr == "" {
		return "未命名"
	}

	parsedURL, err := url.Parse(urlStr)
	if err != nil {
		return "未命名"
	}

	hostname := parsedURL.Hostname()
	if hostname == "" {
		return "未命名"
	}

	// 移除www前缀
	if strings.HasPrefix(hostname, "www.") {
		hostname = hostname[4:]
	}

	return hostname
}

// 保存URL历史记录到文件
func (s *Server) saveUrlHistory() {
	appDataDir, err := getServerAppDataDir()
	if err != nil {
		return
	}

	filepath := filepath.Join(appDataDir, "settings", "url_history.json")
	data, err := json.MarshalIndent(s.urlHistory, "", "  ")
	if err != nil {
		return
	}

	os.WriteFile(filepath, data, 0644)
}

// 从文件加载URL历史记录
func (s *Server) loadUrlHistory() {
	appDataDir, err := getServerAppDataDir()
	if err != nil {
		return
	}

	filepath := filepath.Join(appDataDir, "settings", "url_history.json")
	data, err := os.ReadFile(filepath)
	if err != nil {
		return
	}

	json.Unmarshal(data, &s.urlHistory)
}

// WebView绑定的函数
func (s *Server) SaveTab(tabData map[string]interface{}) error {
	// 保证 body 字段为字符串
	if body, ok := tabData["body"]; !ok || body == nil {
		tabData["body"] = ""
	} else if _, ok := body.(string); !ok {
		tabData["body"] = fmt.Sprintf("%v", body)
	}

	// 排除响应相关数据，不保存到文件中
	delete(tabData, "response")

	// 确保分组字段存在，如果没有则设为默认分组
	if group, ok := tabData["group"]; !ok || group == nil || group == "" {
		tabData["group"] = "默认分组"
	}

	appDataDir, err := getServerAppDataDir()
	if err != nil {
		return err
	}

	tabsDir := filepath.Join(appDataDir, "tabs")

	// 确保tabs目录存在
	if err := os.MkdirAll(tabsDir, 0755); err != nil {
		return err
	}

	// 优先使用 filename 字段作为文件名
	var filename string
	if fname, ok := tabData["filename"].(string); ok && fname != "" {
		filename = fname
	} else {
		// 获取唯一ID
		uniqueId, ok := tabData["uniqueId"].(string)
		if !ok || uniqueId == "" {
			// 如果没有唯一ID，生成一个新的
			uniqueId = fmt.Sprintf("tab_%d_%s", time.Now().UnixNano(), generateRandomString(8))
			tabData["uniqueId"] = uniqueId
		}
		filename = uniqueId + ".json"
	}
	// 保证 tabData["filename"] 字段和实际文件名一致
	tabData["filename"] = filename
	filepath := filepath.Join(tabsDir, filename)

	// 检查文件是否已存在
	if _, err := os.Stat(filepath); err == nil {
		// 文件存在，这是更新操作
		tabData["updatedAt"] = time.Now().Format("2006-01-02 15:04:05")
	} else {
		// 文件不存在，这是新增操作
		tabData["createdAt"] = time.Now().Format("2006-01-02 15:04:05")
		tabData["updatedAt"] = time.Now().Format("2006-01-02 15:04:05")
	}

	data, err := json.MarshalIndent(tabData, "", "  ")
	if err != nil {
		return err
	}

	return os.WriteFile(filepath, data, 0644)
}

// 生成随机字符串
func generateRandomString(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	b := make([]byte, length)
	for i := range b {
		b[i] = charset[mathrand.Intn(len(charset))]
	}
	return string(b)
}

func (s *Server) LoadTab(filename string) (map[string]interface{}, error) {
	appDataDir, err := getAppDataDir()
	if err != nil {
		return nil, err
	}

	filepath := filepath.Join(appDataDir, "tabs", filename)
	data, err := os.ReadFile(filepath)
	if err != nil {
		return nil, err
	}

	var tabData map[string]interface{}
	err = json.Unmarshal(data, &tabData)
	if body, ok := tabData["body"]; !ok || body == nil {
		tabData["body"] = ""
	} else if _, ok := body.(string); !ok {
		tabData["body"] = fmt.Sprintf("%v", body)
	}
	return tabData, err
}

func (s *Server) DeleteTab(filename string) error {
	appDataDir, err := getAppDataDir()
	if err != nil {
		return err
	}

	filepath := filepath.Join(appDataDir, "tabs", filename)
	return os.Remove(filepath)
}

func (s *Server) ClearAllTabs() error {
	appDataDir, err := getAppDataDir()
	if err != nil {
		return err
	}

	tabsDir := filepath.Join(appDataDir, "tabs")
	
	// 读取tabs目录中的所有文件
	files, err := os.ReadDir(tabsDir)
	if err != nil {
		// 如果目录不存在，认为清空成功
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}

	// 删除所有.json文件
	for _, file := range files {
		if !file.IsDir() && strings.HasSuffix(file.Name(), ".json") {
			filepath := filepath.Join(tabsDir, file.Name())
			if err := os.Remove(filepath); err != nil {
				return err
			}
		}
	}

	return nil
}

func (s *Server) GetUrlHistory() []RequestHistoryItem {
	return s.urlHistory
}

func (s *Server) SaveSettings(settings map[string]interface{}) error {
	appDataDir, err := getAppDataDir()
	if err != nil {
		return err
	}

	filepath := filepath.Join(appDataDir, "settings", "config.json")
	data, err := json.MarshalIndent(settings, "", "  ")
	if err != nil {
		return err
	}

	return os.WriteFile(filepath, data, 0644)
}

func (s *Server) LoadSettings() (map[string]interface{}, error) {
	appDataDir, err := getAppDataDir()
	if err != nil {
		return nil, err
	}

	filepath := filepath.Join(appDataDir, "settings", "config.json")
	data, err := os.ReadFile(filepath)
	if err != nil {
		// 返回默认设置
		return map[string]interface{}{
			"theme": "light",
		}, nil
	}

	var settings map[string]interface{}
	err = json.Unmarshal(data, &settings)
	return settings, err
}

func (s *Server) GenerateSignature(params map[string]interface{}) (string, error) {
	// 这里可以实现自定义签名逻辑
	return "", nil
}

func (s *Server) EncryptSM4(data map[string]string) (string, error) {
	body := data["body"]
	key := data["key"]
	iv := data["iv"]

	return s.encryptSM4Body(body, key, iv)
}

func (s *Server) DecryptSM4(data map[string]string) (string, error) {
	body := data["body"]
	key := data["key"]
	iv := data["iv"]

	return s.decryptSM4Response(body, key, iv)
}

// API处理函数
func (s *Server) handleRequest(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	if r.Method == "OPTIONS" {
		return
	}

	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var reqData RequestData
	if err := json.NewDecoder(r.Body).Decode(&reqData); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	response := s.SendRequest(reqData)
	json.NewEncoder(w).Encode(response)
}

func (s *Server) handleSettings(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	if r.Method == "OPTIONS" {
		return
	}

	switch r.Method {
	case "GET":
		settings, err := s.LoadSettings()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		json.NewEncoder(w).Encode(settings)
	case "POST":
		var settings map[string]interface{}
		if err := json.NewDecoder(r.Body).Decode(&settings); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		if err := s.SaveSettings(settings); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(map[string]string{"status": "success"})
	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}

func (s *Server) handleHistory(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	if r.Method == "OPTIONS" {
		return
	}

	switch r.Method {
	case "GET":
		json.NewEncoder(w).Encode(s.GetUrlHistory())

	case "POST":
		var history []RequestHistoryItem
		if err := json.NewDecoder(r.Body).Decode(&history); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		s.urlHistory = history
		s.saveUrlHistory()

		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(map[string]string{"status": "success"})

	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}

func (s *Server) handleTabs(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	if r.Method == "OPTIONS" {
		return
	}

	// 检查是否是获取标签页列表的请求
	if r.URL.Path == "/api/tabs/list" && r.Method == "GET" {
		tabFiles, err := s.GetTabsList()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		json.NewEncoder(w).Encode(tabFiles)
		return
	}

	switch r.Method {
	case "POST":
		var tabData map[string]interface{}
		if err := json.NewDecoder(r.Body).Decode(&tabData); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		if err := s.SaveTab(tabData); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(map[string]string{"status": "success"})

	case "GET":
		// 处理加载特定标签页的请求
		filename := strings.TrimPrefix(r.URL.Path, "/api/tabs/")
		if filename != "" {
			tabData, err := s.LoadTab(filename)
			if err != nil {
				http.Error(w, err.Error(), http.StatusNotFound)
				return
			}
			json.NewEncoder(w).Encode(tabData)
		} else {
			http.Error(w, "Filename required", http.StatusBadRequest)
		}

	case "DELETE":
		// 处理删除标签页的请求
		filename := strings.TrimPrefix(r.URL.Path, "/api/tabs/")
		if filename == "clear" {
			// 清空所有标签页
			if err := s.ClearAllTabs(); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.WriteHeader(http.StatusOK)
			json.NewEncoder(w).Encode(map[string]string{"status": "success"})
		} else if filename != "" {
			if err := s.DeleteTab(filename); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.WriteHeader(http.StatusOK)
			json.NewEncoder(w).Encode(map[string]string{"status": "success"})
		} else {
			http.Error(w, "Filename required", http.StatusBadRequest)
		}

	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}

func (s *Server) handleEncrypt(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	if r.Method == "OPTIONS" {
		return
	}

	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var data map[string]string
	if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	encrypted, err := s.EncryptSM4(data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	response := map[string]string{"encrypted": encrypted}
	json.NewEncoder(w).Encode(response)
}

func (s *Server) handleDecrypt(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	if r.Method == "OPTIONS" {
		return
	}

	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var data map[string]string
	if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	decrypted, err := s.DecryptSM4(data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	response := map[string]string{"decrypted": decrypted}
	json.NewEncoder(w).Encode(response)
}

// 标签页文件信息结构
type TabFileInfo struct {
	Filename string `json:"filename"`
	Name     string `json:"name"`
	Method   string `json:"method"`
	URL      string `json:"url"`
	SavedAt  string `json:"savedAt"`
	Group    string `json:"group"` // 新增：分组字段
}

// 获取已保存的标签页列表
func (s *Server) GetTabsList() ([]TabFileInfo, error) {
	appDataDir, err := getAppDataDir()
	if err != nil {
		return nil, err
	}

	tabsDir := filepath.Join(appDataDir, "tabs")
	files, err := os.ReadDir(tabsDir)
	if err != nil {
		return []TabFileInfo{}, nil // 如果目录不存在，返回空列表
	}

	var tabFiles []TabFileInfo
	for _, file := range files {
		if !file.IsDir() && strings.HasSuffix(file.Name(), ".json") {
			// 读取文件内容获取标签页信息
			filePath := filepath.Join(tabsDir, file.Name())
			data, err := os.ReadFile(filePath)
			if err != nil {
				continue
			}

			var tabData map[string]interface{}
			if err := json.Unmarshal(data, &tabData); err != nil {
				continue
			}

			// 获取文件修改时间
			fileInfo, err := file.Info()
			if err != nil {
				continue
			}

			tabFileInfo := TabFileInfo{
				Filename: file.Name(),
				SavedAt:  fileInfo.ModTime().Format("2006-01-02 15:04:05"),
			}

			// 提取标签页信息
			if name, ok := tabData["name"].(string); ok {
				tabFileInfo.Name = name
			}
			if method, ok := tabData["method"].(string); ok {
				tabFileInfo.Method = method
			}
			if url, ok := tabData["url"].(string); ok {
				tabFileInfo.URL = url
			}
			
			// 提取分组信息，默认为"默认分组"
			group := "默认分组"
			if g, ok := tabData["group"].(string); ok && g != "" {
				group = g
			}
			tabFileInfo.Group = group

			tabFiles = append(tabFiles, tabFileInfo)
		}
	}

	return tabFiles, nil
}

// 环境配置相关数据结构
type EnvironmentType struct {
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`
}

type ProjectEnvironment struct {
	Environment string `json:"environment"`
	BaseURL     string `json:"baseUrl"`
}

type ProjectConfig struct {
	Name         string               `json:"name"`
	ContextPath  string               `json:"contextPath"`
	Environments []ProjectEnvironment `json:"environments"`
}

type EnvironmentConfig struct {
	EnvironmentTypes []EnvironmentType `json:"environmentTypes"`
	ProjectConfigs   []ProjectConfig   `json:"projectConfigs"`
}

// 获取环境配置
func (s *Server) GetEnvironmentConfig() (EnvironmentConfig, error) {
	appDataDir, err := getServerAppDataDir()
	if err != nil {
		return EnvironmentConfig{}, err
	}

	configPath := filepath.Join(appDataDir, "environment.json")
	data, err := os.ReadFile(configPath)
	if err != nil {
		// 如果文件不存在，返回默认配置
		if os.IsNotExist(err) {
			defaultConfig := EnvironmentConfig{
				EnvironmentTypes: []EnvironmentType{
					{Name: "dev", DisplayName: "开发环境"},
					{Name: "qa", DisplayName: "测试环境"},
					{Name: "uat", DisplayName: "预发布环境"},
					{Name: "prod", DisplayName: "生产环境"},
				},
				ProjectConfigs: []ProjectConfig{},
			}
			return defaultConfig, nil
		}
		return EnvironmentConfig{}, err
	}

	var config EnvironmentConfig
	if err := json.Unmarshal(data, &config); err != nil {
		return EnvironmentConfig{}, err
	}

	return config, nil
}

// 保存环境配置
func (s *Server) SaveEnvironmentConfig(config EnvironmentConfig) error {
	appDataDir, err := getServerAppDataDir()
	if err != nil {
		return err
	}

	configPath := filepath.Join(appDataDir, "environment.json")
	data, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		return err
	}

	return os.WriteFile(configPath, data, 0644)
}

// 处理环境配置API请求
func (s *Server) handleEnvironment(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	// 处理预检请求
	if r.Method == "OPTIONS" {
		return
	}
	
	path := r.URL.Path
	
	switch {
	case path == "/api/environment" && r.Method == "GET":
		// 获取环境配置
		config, err := s.GetEnvironmentConfig()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		json.NewEncoder(w).Encode(config)
		
	case path == "/api/environment" && r.Method == "POST":
		// 保存环境配置
		var config EnvironmentConfig
		if err := json.NewDecoder(r.Body).Decode(&config); err != nil {
			http.Error(w, "Invalid JSON", http.StatusBadRequest)
			return
		}
		
		if err := s.SaveEnvironmentConfig(config); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		
		json.NewEncoder(w).Encode(map[string]string{"status": "success"})
		
	default:
		http.Error(w, "Not Found", http.StatusNotFound)
	}
}
